package com.zywl.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zywl.core.beans.Association;
import com.zywl.core.beans.Company;
import com.zywl.core.beans.Member;
import com.zywl.service.AssociationService;
import com.zywl.service.CompanyService;
import com.zywl.service.MemberService;
import com.zywl.service.UserService;
import com.zywl.utils.models.JsonResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.GenerateCodeUtil;
import com.zywl.utils.utils.HttpClientUtil;
import com.zywl.utils.utils.weixin.AccessToken;
import com.zywl.utils.utils.weixin.WeixinUtil;
import com.zywl.web.controller.base.BaseController;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.nio.channels.MembershipKey;
import java.util.*;

/**
 * @author: 徐世相
 * @date: 2020/7/1
 * @description: 微信
 */
@RestController
@RequestMapping("/api/wechat/")
public class WechatApi extends BaseController {
//    private String param="appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
    private String api = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserService userService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private AssociationService associationService;

    /**
     * 微信公众号获取 openid 返回前台
     *
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping("token")
    public JsonResult token(String assId,String code) {
        JsonResult jr = new JsonResult();
        try {
            if(StringUtils.isEmpty(assId)){
                return jr.error("请输入协会id");
            }

            Association association = associationService.getById(Long.valueOf(assId));
            if(association == null){
                return jr.error("协会不存在,请联系平台管理员。");
            }

            logger.info("code==="+code);
            String param="appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
            param = param.replace("APPID",association.getAssWxAppId()).replace("SECRET", association.getAssWxAppSecret())
                    .replace("JSCODE",code);
//            System.out.println(code);
//            System.out.println(param);
            String s = HttpClientUtil.doPost(api, param);
            JSONObject jsonObject = JSONObject.parseObject(s);
            logger.info("jsonObject==="+jsonObject);
            String openId = (String) jsonObject.get("openid");
            String unionId = "";
            if(jsonObject.containsKey("unionid")){
                unionId = (String) jsonObject.get("unionid");
            }
            if (openId != null) {
                jr = CheckBinding(openId,unionId);
            } else {
                jr.error("操作失败");
            }
        } catch (Exception e) {
            logger.error("接口异常", e);
            jr.error("操作失败");
        }
        return jr;
    }

    /**
     * 小程序获取 openid
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping("xcxtoken")
    public JsonResult xcxtoken(String assId,String code) {
        JsonResult jr = new JsonResult();
        try {
            if(StringUtils.isEmpty(assId)){
                return jr.error("请输入协会id");
            }

            Association association = associationService.getById(Long.valueOf(assId));
            if(association == null){
                return jr.error("协会不存在,请联系平台管理员。");
            }

            logger.info("code==="+code);
            String param="appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
            param = param.replace("APPID", association.getAssWxAppId())
                    .replace("SECRET", association.getAssWxAppSecret()).replace("JSCODE",code);
            String s = HttpClientUtil.doPost(api, param);
            JSONObject jsonObject = JSONObject.parseObject(s);
            logger.info("jsonObject==="+jsonObject);
            String openId = (String) jsonObject.get("openid");
            String unionId = "";
            if(jsonObject.containsKey("unionid")){
                unionId = (String) jsonObject.get("unionid");
            }
            if (openId != null) {
                jr = CheckBinding(openId,unionId);
            } else {
                jr.error("获取openId失败，请查询再试");
            }
        } catch (Exception e) {
            logger.error("接口异常", e);
            jr.error("操作失败");
        }
        return jr;
    }


    /**
     * 检测openId是否哟绑定
     *
     * @param openId
     * @return
     */
    @RequestMapping("CheckBinding")
    @ResponseBody
    public JsonResult CheckBinding(String openId,String unionId) {
        JsonResult jr = new JsonResult();
        Map<String, Object> resultMap = new HashMap<>();
        try {
            //查询绑定的人员类型
            Member member = memberService.getByOpenId(openId);
            if(member != null){
                Company company = companyService.getById(member.getMebCompanyId());
                if(company != null && "1".equals(company.getComStt())){
                    jr.error("该公司不存在或者该公司已被禁用，请联系相关负责人！");
                    return jr;
                }
                Association association = associationService.getById(member.getMebAssociationId());
                if(association == null || "1".equals(association.getAssStt())){
                    jr.error("该协会不存在或者该协会已被禁用，请联系相关负责人！");
                    return jr;
                }
                resultMap = BeanUtils.describe(member);
                if(company == null){
                    resultMap.put("islogin", "2");
                }else{
                    resultMap.put("islogin", "0");
                }
            }else{
                resultMap.put("islogin", "1");
            }
            resultMap.put("openId", openId);
            resultMap.put("unionId", unionId);
            jr.success("操作成功",resultMap);
        } catch (Exception e) {
            logger.error("接口异常", e);
            jr.error("操作失败");
        }
        return jr;
    }

    /**
     * 取消认证用户
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("cancelOpenId")
    public JsonResult cancelOpenId(String openId) {
        JsonResult jsonResult = new JsonResult();
        try {
            if(StringUtils.isEmpty(openId)){
                return jsonResult.error("openId不能为空");
            }
            Member member = memberService.getByOpenId(openId);
            if (member != null) {
                member.setMebOpenid(null);
//                member.setUacUnionId(null);
                member.setMebModifyTime(new Date());
                memberService.update(member);
                jsonResult.success("退出成功");
            } else {
                jsonResult.success("无登入用户");
            }
        } catch (Exception e) {
            logger.error("接口异常", e);
            jsonResult.error("操作失败");
        }
        return jsonResult;
    }

    /**
     * 取消认证用户
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("cancelUnionId")
    public JsonResult cancelUnionId(String unionId) {
        JsonResult jsonResult = new JsonResult();
        try {
            if(StringUtils.isEmpty(unionId)){
                return jsonResult.error("unionId不能为空");
            }
           /* UserAccount userAccount = userAccountService.getByUnionId(unionId);
            if (userAccount != null) {
                userAccount.setUacOpenId(null);
                userAccount.setUacUnionId(null);
                userAccount.setUacModifyTime(new Date());
                userAccountService.update(userAccount);
                jsonResult.success("退出成功");
            } else {
                jsonResult.success("无认证用户");
            }*/
        } catch (Exception e) {
            logger.error("接口异常", e);
            jsonResult.error("操作失败");
        }
        return jsonResult;
    }


    private String access_token  = "";
    private Long expiresIn = (long)0;
    public final static String get_user_phone_number_url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=ACCESS_TOKEN";

    @ResponseBody
    @RequestMapping("/getPhoneNum")//获取手机号
    public JsonResult getPhoneNum(String jsCode,Long assId,String openId,String unionId) {
        JsonResult jr = new JsonResult();
        Date date = new Date();
        long newTime = date.getTime() / 1000;
        try {
            if(StringUtils.isEmpty(assId +"")){
                return jr.error("请输入协会id");
            }

            Association association = associationService.getById(assId);
            if(association == null){
                return jr.error("协会不存在,请联系平台管理员。");
            }

            if(StringUtils.isEmpty(access_token) || newTime > expiresIn){
                AccessToken accessToken = WeixinUtil.getAccessToken(association.getAssWxAppId(),association.getAssWxAppSecret());
                access_token = accessToken.getToken();
                expiresIn = newTime + 6800;
            }
            //使用获取到的token和接受到的code像微信获取手机号
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", jsCode);
//            logger.info("code" + jsCode);
            String requestUrl = get_user_phone_number_url.replace("ACCESS_TOKEN", access_token);
            String s = HttpClientUtil.doPost(requestUrl, jsonObject.toString());
//            logger.info("微信授权" + s);
            JSONObject returns = JSON.parseObject(s);
            String phoneInfo = returns.getString("phone_info");
            JSONObject phoneInfos = JSON.parseObject(phoneInfo);
            String phone = phoneInfos.getString("phoneNumber");//用户绑定的手机号（国外手机号会有区号）

            //查询数据库 是否存在，如果不存在就创建
            Map<String,Object> map = new HashMap<>();
            map.put("meb_username",phone);
            map.put("meb_stt","0");
            List<Member> memberList = memberService.getListByParams(map);
            Member member = null;
            if(memberList.size() == 0){
                member = new Member();
                member.setMebAssociationId(assId);
                member.setMebType("1");
                member.setMebUsername(phone);
                member.setMebMobile(phone);
                member.setMebPassword(GenerateCodeUtil.MD5("123456"));
                member.setMebStt("0");
                member.setMebCreateTime(date);
                member.setMebModifyTime(date);
                member.setMebLastLoginTime(date);
                member.setMebOpenid(openId);
                memberService.save(member);
            }else{
                member = memberList.get(0);
                member.setMebOpenid(openId);
                member.setMebModifyTime(date);
                member.setMebLastLoginTime(date);
                memberService.update(member);
            }
            Map<String,Object> resultMap = BeanUtils.describe(member);
            if(member.getMebCompanyId() == null){
                resultMap.put("islogin", "2");
            }else{
                resultMap.put("islogin", "0");
            }
            jr.success("授权登入成功",resultMap);
        }catch (Exception e){
            logger.error("获取用户电话失败",e);
            jr.error("授权登入失败");
        }
         return jr;
    }

}

